package com.xieh.mail.service;


import javafx.util.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import freemarker.template.Configuration;
import javax.mail.internet.MimeMessage;


import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author 谢辉
 * @Classname MailService
 * @Description TODO
 * @Date 2020/11/24 10:08
 */
@Component
public class MailService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String sender;

    /**
     * 用来发送模版邮件
     */
    @Autowired
    private TemplateEngine templateEngine;

    //发送邮件的模板引擎
    @Autowired
    private FreeMarkerConfigurer configurer;


    /**
     * 发送简单的邮件
     * @param receiver 接收者
     * @param subject 主题
     * @param context 内容
     */
    public void sendSimpleMail(String receiver,String subject, String context){
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(sender);
        mailMessage.setTo(receiver);
        mailMessage.setSubject(subject);
        mailMessage.setText(context);
        try {
            mailSender.send(mailMessage);
            logger.info("简单邮件发送成功!接收者是：" + receiver);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("简单邮件发送失败!");
        }
    }


    /**
     * 发送html的邮件
     * @param receiver 接收者
     * @param subject 主题
     * @param context 内容
     */
    public void sendHtmlMail(String receiver,String subject, String context){
        MimeMessage mimeMailMessage = mailSender.createMimeMessage();
        try{
            MimeMessageHelper helper = new MimeMessageHelper(mimeMailMessage,true,"UTF-8");
            helper.setFrom(sender);
            helper.setTo(receiver);
            helper.setSubject(subject);
            helper.setText(context,true);
            mailSender.send(mimeMailMessage);
            logger.info("html邮件发送成功！接收者是:" + receiver);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("html邮件发送失败！");
        }
    }


    /**
     * 使用Freemarker模板发送邮件
     * @param receiver 接收者
     * @param subject 主题
     * @param params 参数
     */
    public void sendFreemarkerTemplateMail(String receiver, String subject, Map<String, Object> params){
        MimeMessage mimeMailMessage = mailSender.createMimeMessage();
        try{
            MimeMessageHelper helper = new MimeMessageHelper(mimeMailMessage,true,"UTF-8");
            helper.setFrom(sender);
            helper.setTo(receiver);
            helper.setSubject(subject);
            Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
            //设置编码
            configuration.setDefaultEncoding("utf-8");
            //ftl模板文件
            configuration.setClassForTemplateLoading(this.getClass(), "/static/");

            String html = FreeMarkerTemplateUtils.processTemplateIntoString(configuration.getTemplate("mail.ftl"), params);
            helper.setText(html, true);//重点，默认为false，显示原始html代码，无效果
            mailSender.send(mimeMailMessage);
            logger.info("Freemarker邮件发送成功！接收者是:" + receiver);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("Freemarker邮件发送失败！");
        }

    }

    /**
     * 使用Thymeleaf模板发送邮件
     * @param receiver 接收者
     * @param subject 主题
     * @param params 参数
     */
    public void  sendThymeleafTemplateMail(String receiver, String subject, Map<String, Object> params){
        MimeMessage mimeMailMessage = mailSender.createMimeMessage();
        //创建邮件正文
        Context context = new Context();
        if(params != null){
           Set<Map.Entry<String, Object>> entrySet = params.entrySet();
           for (Map.Entry<String, Object> entry : entrySet){
               context.setVariable(entry.getKey(),entry.getValue());
           }
        }
        try{
            MimeMessageHelper helper = new MimeMessageHelper(mimeMailMessage,true,"UTF-8");
           /* context.setVariable("user", "1111");
            context.setVariable("web", "tttt");
            context.setVariable("company", "我是一个公司");
            context.setVariable("product","我是一个产品");*/
            helper.setFrom(sender);
            helper.setTo(receiver);
            helper.setSubject(subject);

            // 这里是去找（resources的）templates目录下的mail目录下的mail.html文件
            //  String emailContent = templateEngine.process("/mail/mail",context); //指定模板路径

            // 这里是去找（resources的）templates目录下的emailTemplate.html文件
            String emailContent = templateEngine.process("emailTemplate", context);
            helper.setText(emailContent,true);
            mailSender.send(mimeMailMessage);
            logger.info("Thymeleaf邮件发送成功！接收者是:" + receiver);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("Thymeleaf邮件发送失败！");
        }
    }


    /**
     * 发送带附件的邮件
     * @param receiver 接收者
     * @param subject 主题
     * @param context 内容
     * @param attachments 附件
     */
    public void sendAttachmentsMail(String receiver, String subject, String context, List<Pair<String, File>> attachments) {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(message, true,"UTF-8");
            helper.setFrom(sender);
            helper.setTo(receiver);
            helper.setSubject(subject);
            helper.setText(context, true);
            if(attachments != null){
                for(Pair<String,File> attachment:attachments){
                    FileSystemResource file = new FileSystemResource(attachment.getValue());
                    helper.addAttachment(attachment.getKey(), file);
                }
            }
            mailSender.send(message);
            logger.info("附件邮件发送成功！接收者是:" + receiver);
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("附件邮件发送失败！");
        }
    }




}
